package com.example.hash;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.Map;

@Service
public class GetTestImpl implements GetTextMapper {

    String MemoryPath="D:\\javaproject\\hash\\src\\main\\resources\\file\\memoryHash";

    @Override
    public String onlyText(String filePath) {
        try {
            // 获取文件输入流
            Path path = Paths.get(filePath);
            InputStream inputStream = Files.newInputStream(path);

            // 创建MessageDigest实例 (这里使用SHA-256)
            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            // 读取文件并更新哈希计算
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                digest.update(buffer, 0, bytesRead);
            }

            // 完成哈希计算并转换为十六进制字符串
            byte[] hashBytes = digest.digest();
            String result=HexFormat.of().formatHex(hashBytes);
            writeToLogFile(MemoryPath, result);
            return HexFormat.of().formatHex(hashBytes);

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256算法不可用", e);
        } catch (Exception e) {
            throw new RuntimeException("读取文件或计算哈希时出错: " + e.getMessage(), e);
        }
    }

    @Override
    public Map<String, String> allText(String dirPath){
        Map<String, String> fileHashes = new HashMap<>();
        try {
            Files.walk(Paths.get(dirPath))
                    .filter(Files::isRegularFile)
                    .forEach(file -> {
                        fileHashes.put(
                                file.toString(),
                                calculateFileHash(file)
                        );
                    });
        } catch (IOException e) {
            throw new RuntimeException("遍历目录失败: " + e.getMessage(), e);
        }
        return fileHashes;
    }


    private String calculateFileHash(Path filePath) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] fileBytes = Files.readAllBytes(filePath);
            byte[] hashBytes = digest.digest(fileBytes);
            return bytesToHex(hashBytes);
        } catch (Exception e) {
            throw new RuntimeException("计算哈希失败: " + filePath, e);
        }
    }


    private static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

}
